import { patrolingCruise } from '@/api'
import { useCarStore } from '@/stores/car'
import { initWebSocket } from '@/utils'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useVoiceStore = defineStore('voice', () => {
  const car = useCarStore()
  const talkBack = ref(false)
  let ws: WebSocket | null
  let mediaRecorder: MediaRecorder

  function handleTalkBack(val: boolean) {
    talkBack.value = val
    const data = {
      code: car.currentCar,
      param1: 5,
      param2: val ? 1 : 2,
      param3: 255,
      param4: 255
    }
    patrolingCruise(data)

    if (val) {
      record()
    } else {
      clear()
    }
  }

  function clear() {
    mediaRecorder.stop()
    ws && ws.close()
    ws = null
  }

  async function record() {
    ws = initWebSocket('/websocket/audio/shout', {
      onmessage() {},
      async onopen() {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        const options = {
          mimeType: 'audio/webm'
        }
        mediaRecorder = new MediaRecorder(stream, options)
        mediaRecorder.ondataavailable = ondataavailable
        mediaRecorder.start(50)
      }
    })
  }

  async function ondataavailable(e: BlobEvent) {
    await Promise.resolve()
    ws && ws.send(e.data)
  }

  return {
    talkBack,
    handleTalkBack,
    ondataavailable
  }
})
